requirejs.config({
	baseUrl: '/tb/Public/',
	paths: {
		jquery:'bower_components/jquery/jquery.min',
		imgareaselect:'jquery.imgareaselect-0.9.10/jquery.imgareaselect.min',
		uploadify:'uploadify/jquery.uploadify.min'
	},
	shim:{
		'imgareaselect':['jquery'],
		'uploadify':['jquery'],
	}
});
var requireApp = ["jquery","imgareaselect","uploadify"];
//JSON检测
if(  typeof JSON === 'undefined' ){
	requireApp.push('json2');
}
//调用依赖
require(requireApp, function($) {
	var $ = $.noConflict();
	
	var imgArea;
	var $uploaded,
	$previewWrap = $("#cut-preview-wrap"),
	$preview = $("#cut-preview");
	
	var $field = $("input[type='file']");
	$field.uploadify({
		'buttonText': '选择图片',
		'swf': '/tb/Public/uploadify/uploadify.swf?v=' + ( parseInt(Math.random()*1000) ),
		'uploader'  : '/tb/index.php/Admin/Upload/uploadImg',
		'auto'      : false,
		'multi'     : false,//是否支持多文件上传
		'method'    : 'post',
		'fileObjName' : 'upload',
		'queueSizeLimit' : 1,//队列大小限制
		'simUploadLimit' :1,//每次上传图片次数
		'fileSizeLimit' : '3000KB',
		'fileTypeExts': '*.gif; *.jpg; *.png; *.jpeg',
		'fileTypeDesc': '只允许.gif .jpg .png .jpeg 图片！',
		'onSelect': function(file) {//选择文件后的触发事件
//			$("#upload").show();
			$field.uploadify('upload','*');
		},
		'onInit': function () {                        //载入时触发，将flash设置到最小
			$("#file-queue").hide();
		},
		'onUploadSuccess' : function(file, data, response){  //上传成功后的触发事件
//			$field.uploadify('disable', true);
//			console.log(data);

			var rst =JSON.parse(data);
			if( rst.status == 0 ){
				alert('上传失败:'+rst.info);
			}else{
				var imageData = rst.data;
				var $image = $("<img src='"+imageData.path+"' id='image-uploaded' data-width='"+imageData.width+"' data-height='"+imageData.height+"' data-name='"+imageData.name+"' />");
				$("#uploaded-wrap").html( $image );
				$uploaded = $("#image-uploaded")
//				$("#uploaded-wrap").append( $image ).show();
				$("#file-button").hide();
				$("#upload-wrap").show();
//				$("#ratio-wrap").show();
//				$image.bind('click',function(e){
//				e.preventDefault();
//				alert('请先设置裁剪宽高比！');
//				});
				var ratio = 16/9;
//				console.log(ratio);
				//相关元素

				//图片宽高参数
				var realWidth = imageData.width,
				realHeight = imageData.height,
				uploadedWidth = $("#uploaded-wrap").outerWidth()-30,
				uploadedRate = uploadedWidth/realWidth; //缩放比例
				uploadedHeight = uploadedRate*realHeight,

//				console.log("uploadedWidth:"+uploadedWidth+"\nuploadedHeight:"+uploadedHeight);
				$("#cut-help").html('图片宽:'+realWidth+' 高:'+realHeight+' 裁剪比例:'+ratio+'<strong style="color:red;"> 在图片上进行拖拽确定裁剪区域！</strong>');
				$("#preview-wrap").show();

				//预览框宽高参数
				var previewWrapWidth = $previewWrap.outerWidth();
				previewWrapHeight = Math.round(previewWrapWidth/ratio);

				//初始化预览框
				$previewWrap.css( {
					width:previewWrapWidth+'px',
					height:previewWrapHeight+'px'
				} );
				//初始化预览图
				$preview.prop( 'src',$image.attr('src') );

				//构造AreaSelect选择器
				imgArea = $image.imgAreaSelect({
					instance: true,  
					handles: true,   
					fadeSpeed: 300,
					aspectRatio:'1:'+(1/ratio),
					//选区改变时的触发事件
					onSelectChange: function(img,selection){//selection包括x1,y1,x2,y2,width,height，分别为选区的偏移和高宽。
						var rate = previewWrapWidth/selection.width;//预览区相对于选择区的倍数
						$preview.css({
							width: Math.round(uploadedWidth*rate)+'px',
							height: Math.round(uploadedHeight*rate)+'px',
							"left": Math.round(selection.x1*rate*-1),
							"top": Math.round(selection.y1*rate*-1) 
						});

						//换算后的真实参数
						var realSize = {
								width:     Math.round(selection.width/uploadedRate),
								height:    Math.round(selection.height/uploadedRate),
								offsetLeft:Math.round(selection.x1/uploadedRate),
								offsetTop: Math.round(selection.y1/uploadedRate)
						}
						$preview.data( realSize );
					}
				});
				$("#cut").show();
			}
		}
		,'onUploadError' : function(file, errorCode, errorMsg, errorString){
			alert(errorString);
		}
	});
	
	//点击确认裁剪时
	$("#cut").click(function(e){
		e.preventDefault();
		var $this = $(this);
		var data = $preview.data();
//		console.log(data);
		if( typeof data['width'] === 'undefined' ||
				data['width'] == ''||
				data['width'] == 0 ||
				data['height'] == '' ||
				data['height'] == 0 ){
			alert('请先选择裁剪区域！');
			return ;
		}

//		$this.addClass('active').text('裁剪中...');
		data['name'] = $uploaded.data('name');
//		console.log(data);
		$.ajax({
			url:'/tb/index.php/Admin/Upload/cutImg',
			type:'POST',
			data:data,
			success: function(data){
//				console.log(data);
//				var rst = JSON.parse(data);
				if( data.status == 0 ){
					alert('失败!'+rst.info);
				}else{
					imgArea.setOptions({'disable':true,'hide':true});//去掉选区功能
					var imagewidth = $("#image").outerWidth()/3;
					var imageRate = imagewidth / data.width;
					var imageheight = imageRate*data.height;
					
					 
					var $image = $("<div class='col-xs-4'><img src='"+data.path+"' style='width:"+imagewidth+"px;height:"+imageheight+"px'/><input type='hidden' name='image[]' value='"+data.path+"'/></div>");
					$("#upload-img").append($image);
					$("#file-button").show();
					$("#upload-wrap").hide();
					$("#cut").hide();
//					$("#image").val(data.path);
//					$("#uploadImage").html($image);
				}
			}
		});
	});
});
